
/**
 * 将时间解析为字符串
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
function parseTime(time, cFormat) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string')) {
            if ((/^[0-9]+$/.test(time))) {
                // support "1548221490638"
                time = parseInt(time)
            } else {
                // support safari
                // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
                time = time.replace(new RegExp(/-/gm), '/')
            }
        }

        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        return value.toString().padStart(2, '0')
    })
    return time_str
}

/**
 * 判断当前时间状态
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
function formatTime(time, option) {
    if (('' + time).length === 10) {
        time = parseInt(time) * 1000
    } else {
        time = +time
    }
    const d = new Date(time)
    const now = Date.now()

    const diff = (now - d) / 1000

    if (diff < 30) {
        return '刚刚'
    } else if (diff < 3600) {
        // less 1 hour
        return Math.ceil(diff / 60) + '分钟前'
    } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前'
    } else if (diff < 3600 * 24 * 2) {
        return '1天前'
    }
    if (option) {
        return parseTime(time, option)
    } else {
        return (
            d.getMonth() +
            1 +
            '月' +
            d.getDate() +
            '日' +
            d.getHours() +
            '时' +
            d.getMinutes() +
            '分'
        )
    }
}

/**
 * 获取url参数
 * @param {string} url
 * @returns {Object}
 */
function getQueryObject(url) {
    url = url == null ? window.location.href : url
    const search = url.substring(url.lastIndexOf('?') + 1)
    const obj = {}
    const reg = /([^?&=]+)=([^?&=]*)/g
    search.replace(reg, (rs, $1, $2) => {
        const name = decodeURIComponent($1)
        let val = decodeURIComponent($2)
        val = String(val)
        obj[name] = val
        return rs
    })
    return obj
}

/**
 * 获取字节长度
 * @param {string} input value
 * @returns {number} output value
 */
function byteLength(str) {
    // returns the byte length of an utf8 string
    let s = str.length
    for (var i = str.length - 1; i >= 0; i--) {
        const code = str.charCodeAt(i)
        if (code > 0x7f && code <= 0x7ff) {
            s++
        } else if (code > 0x7ff && code <= 0xffff) s += 2
        if (code >= 0xDC00 && code <= 0xDFFF) i--
    }
    return s
}

/**
 * 判断字符串中某字符出现的次数
 * @param {string} str
 * @param {string} char
 * @returns {number} 
 */
function countOccurrences(str, char) {
    const regex = new RegExp(char, 'g');
    const matches = str.match(regex);
    return matches ? matches.length : 0;
}

/**
 * 获取当前绝对路径距登录页层数
 * @returns {string} 
 */
function absolutepath() {
    var currentURL = window.location.href;
    var str = "";
    if (currentURL.includes('view')) {
        var relativePath = currentURL.substring(currentURL.lastIndexOf("view"), currentURL.length);
        for (let i = 0; i < countOccurrences(relativePath, '/'); i++) {
            str = str.concat('../');
        }
    }
    return str;
}

/**
 * 整理数组
 * @param {Array} actual
 * @returns {Array}
 */
function cleanArray(actual) {
    const newArray = []
    for (let i = 0; i < actual.length; i++) {
        if (actual[i]) {
            newArray.push(actual[i])
        }
    }
    return newArray
}

/**
 * 浮点型相加
 * @param {String} arg1 浮点型数
 * @param {String} arg2 浮点型数
 * @returns 
 */
function accAdd(arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2))
    return (arg1 * m + arg2 * m) / m
}

/**
 * 浮点型相减
 * @param {String} arg1 浮点型数
 * @param {String} arg2 浮点型数
 * @returns 
 */
function accSub(arg1, arg2) {
    return accAdd(arg1, -arg2);
}

/**
 * 浮点型相乘
 * @param {String} arg1 浮点型数
 * @param {String} arg2 浮点型数
 * @returns 
 */
function accMul(arg1, arg2) {
    let m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try { m += s1.split(".")[1].length } catch (e) { }
    try { m += s2.split(".")[1].length } catch (e) { }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
/**
 * 浮点型相除
 * @param {String} arg1 浮点型数
 * @param {String} arg2 浮点型数
 * @returns 
 */
function accDiv(arg1, arg2) {
    var t1 = 0, t2 = 0, r1, r2;
    try { t1 = arg1.toString().split(".")[1].length; } catch (e) { t1 = 0; }
    try { t2 = arg2.toString().split(".")[1].length; } catch (e) { t2 = 0; }
    r1 = Number(arg1.toString().replace(".", ""));
    r2 = Number(arg2.toString().replace(".", ""));
    return accMul(r1 / r2, Math.pow(10, t2 - t1));
}

/**
 * 千分位处理
 * @param {String} str 待处理字段
 * @returns 
 */
function thousands(str) {
    str = Number(str).toFixed(2)
    return str.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

/**
 * 百分比处理
 * @param {*} str 待处理字段
 * @returns 
 */
function percentage(str) {
    str = Number(str * 100).toFixed(2);
    return str += "%";
}

/**
 * 前/后置补零
 * @param {Number} number 数字
 * @param {Number} length 补零长度
 * @param {Number} type 0前置补零 1后置补零
 */
function addZero(number, length, type = 0) {
    let str = number.toString(); // 将数字转换为字符串
    while (str.length < length) {
        if (!type) {
            str = "0" + str; // 在字符串前面添加零
        } else {
            str = str + "0"; // 在字符串前面添加零
        }
    }
    return str;
}

/**
 * 转译json
 * @param {Object} json
 * @returns {Array}
 */
function param(json) {
    if (!json) return ''
    return cleanArray(
        Object.keys(json).map(key => {
            if (json[key] === undefined) return ''
            return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
        })
    ).join('&')
}

/**
 * 获取导航栏参数
 * @param {string} url
 * @returns {Object}
 */
function param2Obj(url) {
    const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
    if (!search) {
        return {}
    }
    const obj = {}
    const searchArr = search.split('&')
    searchArr.forEach(v => {
        const index = v.indexOf('=')
        if (index !== -1) {
            const name = v.substring(0, index)
            const val = v.substring(index + 1, v.length)
            obj[name] = val
        }
    })
    return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
function html2Text(val) {
    const div = document.createElement('div')
    div.innerHTML = val
    return div.textContent || div.innerText
}

/**
 * 合并两个对象，赋予最后一个对象优先级
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
function objectMerge(target, source) {
    if (typeof target !== 'object') {
        target = {}
    }
    if (Array.isArray(source)) {
        return source.slice()
    }
    Object.keys(source).forEach(property => {
        const sourceProperty = source[property]
        if (typeof sourceProperty === 'object') {
            target[property] = objectMerge(target[property], sourceProperty)
        } else {
            target[property] = sourceProperty
        }
    })
    return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
function toggleClass(element, className) {
    if (!element || !className) {
        return
    }
    let classString = element.className
    const nameIndex = classString.indexOf(className)
    if (nameIndex === -1) {
        classString += '' + className
    } else {
        classString =
            classString.substr(0, nameIndex) +
            classString.substr(nameIndex + className.length)
    }
    element.className = classString
}

/**
 * 获取90天前时间戳
 * @param {string} type
 * @returns {Date}
 */
function getTime(type) {
    if (type === 'start') {
        return new Date().getTime() - 3600 * 1000 * 24 * 90
    } else {
        return new Date(new Date().toDateString())
    }
}

/**
 * 去抖动
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
function debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result

    const later = function () {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp

        // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
            if (!immediate) {
                result = func.apply(context, args)
                if (!timeout) context = args = null
            }
        }
    }

    return function (...args) {
        context = this
        timestamp = +new Date()
        const callNow = immediate && !timeout
        // 如果延时不存在，重新设定延时
        if (!timeout) timeout = setTimeout(later, wait)
        if (callNow) {
            result = func.apply(context, args)
            context = args = null
        }

        return result
    }
}

/**
 * 这只是深度复制的一个简单版本
 * This is just a simple version of deep copy
 * 有很多边缘案例错误
 * Has a lot of edge cases bug
 * 如果你想使用完美的深度复制，请使用lodash的_.cloneDeep
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
function deepClone(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'deepClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    Object.keys(source).forEach(keys => {
        if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = deepClone(source[keys])
        } else {
            targetObj[keys] = source[keys]
        }
    })
    return targetObj
}

/**
 * 将对象添加原值，形成Original结构
 * @param {Object} form 
 */
function configOriginal(form) {
    let obj = deepClone(form);
    for (let key in obj) {
        if (key == "Children") {
            for (let ChildKey in obj[key]) {
                for (let i = 0; i < obj[key][ChildKey].length; i++) {
                    configOriginal(obj[key][ChildKey][i]);
                }
            }
        } else {
            if (!key.includes("_Original") && !obj.hasOwnProperty(key + "_Original")) {
                obj[key + "_Original"] = obj[key];
            }
        }
    }
    return obj
}

/**
 * 去重数组
 * @param {Array} arr
 * @returns {Array}
 */
function uniqueArr(arr) {
    return Array.from(new Set(arr))
}

/**
 * 将驼峰命名改成-间隔
 * @param {String} str 
 * @returns 
 */
function camelToKebab(str) {
    return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}

/**
 * 判断数组中对象某属性是否全部相等
 * @param {Array} arr JSON数组
 * @param {String} key Object中某属性名
 * @returns 
 */
function checkPropertiesEquality(arr, key) {
    if (arr.length === 0) {
        return true; // 空数组默认属性全部相等
    }
    const referenceValue = arr[0][key] // 获取第一个元素的属性值作为参考值
    for (let i = 1; i < arr.length; i++) {
        const propertyValue = arr[i][key] // 获取当前元素的属性值
        if (propertyValue != referenceValue) {
            return false; // 发现不相等的属性值，返回false
        }
    }
    return true; // 所有元素的属性值都相等，返回true
}

/**
 * 随机生成唯一字符串
 * @returns {string}
 */
function createUniqueString() {
    const timestamp = +new Date() + ''
    const randomNum = parseInt((1 + Math.random()) * 65536) + ''
    return (+(randomNum + timestamp)).toString(32)
}

/**
 * 检查元素是否有类
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
function hasClass(ele, cls) {
    return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * 将类添加到元素
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
function addClass(ele, cls) {
    if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * 从元素中删除类
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
        const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
        ele.className = ele.className.replace(reg, ' ')
    }
}
/**
 * 掩码
 * @param {*} length 
 * @param {*} mask 
 * @returns 
 */
function createMaskedString(allowedChars, length, mask) {
    let result = '';
    for (let i = 0; i < length; i++) {
        result += allowedChars.charAt(Math.floor(Math.random() * allowedChars.length));
    }
    return result.padStart(length, mask);
}

/**
 * 判断是否预期
 * @param {Date} date1
 * @param {Date} date2
 * @returns
 */
function tabDay(date1, date2) {
    var oDate1 = new Date(date1);
    var oDate2 = new Date(date2);
    if (oDate1.getTime() > oDate2.getTime()) {
        return true;
    } else {
        return false;
    }
}

/**
 * 给base64编码头，去掉（base64编码头部：data:image/jpeg;base64）
 * @param {String} str 
 * @returns 
 */
function base64head(str) {
    let i = str.indexOf(",");
    return str.substring(i + 1)
}

/**
 * 判断两个时间是否为同年同月同日
 * @param {Date} date1
 * @param {Date} date2
 * @returns {boolean}
 */
function tabMonth(date1, date2) {
    var oDate1 = new Date(date1);
    var oDate2 = new Date(date2);
    if (oDate1.getFullYear() == oDate2.getFullYear() && oDate1.getMonth() == oDate2.getMonth() && oDate1.getDate() == oDate2.getDate()) {
        return true;
    } else {
        return false;
    }
}
/**
 * 获取当前年月
 * @returns {string}
 */
function getYMDate() {
    var data = new Date();
    let m = data.getMonth() + 1;
    if (m < 10) {
        m = "0" + m
    }
    return data.getFullYear() + "-" + m
}

/**
 * 生成自定义位数验证码
 */
function generateCode(num = 6) {
    let code = '';
    for (let i = 0; i < num; i++) {
        code += parseInt(Math.random() * 10);
    }
    //如果首位是0，则继续生成，直到首位不为0为止
    while (code.startsWith('0')) {
        code = '' + Math.floor(Math.random() * 10) + code.slice(1);
    }
    return code
}

/**
 * 获取日期 年-月-日 时:分:秒
 * @returns {}
 */
function getYMDHMSDate(oDate) {
    if (oDate != null) {
        var data = new Date(oDate);
    } else {
        var data = new Date();
    }
    let m = data.getMonth() + 1;
    let d = data.getDate();
    let H = data.getHours();
    let M = data.getMinutes();
    let S = data.getSeconds();
    if (m < 10) {
        m = "0" + m
    }
    if (d < 10) {
        d = "0" + d
    }
    if (H < 10) {
        H = "0" + H
    }
    if (M < 10) {
        M = "0" + M
    }
    if (S < 10) {
        S = "0" + S
    }
    return data.getFullYear() + "-" + m + "-" + d + " " + H + ":" + M + ":" + S
}

/**
 * 获取日期 年-月-日
 * @returns {}
 */
function getYMDDate(oDate) {
    if (oDate != null) {
        var data = new Date(oDate);
    } else {
        var data = new Date();
    }
    let m = data.getMonth() + 1;
    let d = data.getDate();
    if (m < 10) {
        m = "0" + m
    }
    if (d < 10) {
        d = "0" + d
    }
    return data.getFullYear() + "-" + m + "-" + d
}

/**
 * 获取当前时间戳，单位秒
 * @returns
 */
function getCurrentTimestamp() {
    return Math.floor(Date.now() / 1000);
}

function getTimeSlot() {
    let message = ''
    //通过内置构造函数Date
    let hours = new Date().getHours()
    if (hours <= 9) {
        message = '早上'
    } else if (hours <= 12) {
        message = '上午'
    } else if (hours <= 18) {
        message = '下午'
    } else {
        message = '晚上'
    }
    return message
}

/**
 * 获取倒计时
 * @param {*} date 
 * @returns 
 */
function getCountDown(date) {
    let now = new Date();
    let future = new Date(date)//距离的时间
    let index = (future - now) / 1000 / (60 * 60 * 24)
    let day = parseInt(index)//天
    let h = parseInt((index - day) * 24)//时
    let m = parseInt((index - day - h / 24) * 24 * 60)//分
    let s = parseInt((index - day - h / 24 - m / 60 / 24) * 24 * 60 * 60)//秒
    return { day, h, m, s }
}

//将数字转换为汉字
function toChinesNum(num) {
    let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']; //changeNum[0] = "零"
    let unit = ["", "十", "百", "千", "万"];
    num = parseInt(num);
    let getWan = (temp) => {
        let strArr = temp.toString().split("").reverse();
        let newNum = "";
        for (var i = 0; i < strArr.length; i++) {
            newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
        }
        return newNum;
    }
    let overWan = Math.floor(num / 10000);
    let noWan = num % 10000;
    if (noWan.toString().length < 4) noWan = "0" + noWan;
    return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);

}
/**
 * 实现冒泡排序
 * @param {*} arr 数组
 * @param {*} str 标识
 * @returns 
 */
function sort(arr, str) {
    for (var i = 0; i < arr.length - 1; i++) {
        // 内层循环,控制比较的次数，并且判断两个数的大小
        for (var j = 0; j < arr.length - 1 - i; j++) {
            if (str) {
                if (arr[j][str] > arr[j + 1][str]) {
                    var temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            } else {
                if (arr[j] > arr[j + 1]) {
                    var temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    return arr
}
// 通过时间获取几年前
const pickerOptions = {
    shortcuts: [{
        text: '今天',
        onClick(picker) {
            picker.$emit('pick', new Date())
        }
    }, {
        text: '昨天',
        onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
        }
    }, {
        text: '一周前',
        onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
        }
    }]
}
// 通过时间获取几年前
const pickerOptionsTwo = {
    shortcuts: [{
        text: '今天',
        onClick(picker) {
            picker.$emit('pick', [getYMDDate() + ' 00:00:00', getYMDHMSDate()])
        }
    }, {
        text: '一周前',
        onClick(picker) {
            const end = new Date().getTime();
            const start = end - 7 * 24 * 60 * 60 * 1000;
            picker.$emit('pick', [getYMDHMSDate(start), getYMDHMSDate(end)]);
        }
    }, {
        text: '一月前',
        onClick(picker) {
            const end = new Date().getTime();
            const start = end - 30 * 24 * 60 * 60 * 1000;
            picker.$emit('pick', [getYMDHMSDate(start), getYMDHMSDate(end)]);
        }
    }]
}

/**
 * 获取1%~100%对应浮点型json
 * @returns {Array}
 */
function getPercentage() {
    var list = new Array();
    for (var i = 1; i <= 100; i++) {
        var obj = {
            "key": i + "%",
            "value": i / 100 + ""
        }
        list.push(obj)
    }
    return list;
}
/**
 * 获取56民族
 * @returns {Array}
 */
function national() {
    return [
        "汉族", "壮族", "满族", "回族", "苗族", "维吾尔族", "土家族", "彝族", "蒙古族", "藏族", "布依族", "侗族", "瑶族", "朝鲜族", "白族", "哈尼族",
        "哈萨克族", "黎族", "傣族", "畲族", "傈僳族", "仡佬族", "东乡族", "高山族", "拉祜族", "水族", "佤族", "纳西族", "羌族", "土族", "仫佬族",
        "锡伯族",
        "柯尔克孜族", "达斡尔族", "景颇族", "毛南族", "撒拉族", "布朗族", "塔吉克族", "阿昌族", "普米族", "鄂温克族", "怒族", "京族", "基诺族", "德昂族",
        "保安族",
        "俄罗斯族", "裕固族", "乌孜别克族", "门巴族", "鄂伦春族", "独龙族", "塔塔尔族", "赫哲族", "珞巴族"
    ]
}
//获取学历
function ducation() {
    return ["初中及以下", "高中", "中专/中技", "大专", "本科", "硕士", "博士"]
}

function thousands(params) {
    params = Number(params).toFixed(2)
    return params.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

